package com.healthySys.backend.config.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.healthySys.common.result.Result;
import com.healthySys.common.utils.JWTStoreUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 用户登出处理
 */
@Component
@Slf4j
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private JWTStoreUtil jwtStoreUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, IOException {

        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(7);
        Claims claims = JWTStoreUtil.parseJWT(token);

        String username = claims.getSubject();

        response.setContentType("application/json;charset=UTF-8");

        log.info("{}用户:正在登出",username);
        jwtStoreUtil.removeStoredJWT(username);

        SecurityContextHolder.clearContext();

        response.getWriter().write(
            new ObjectMapper().writeValueAsString(
                Result.success(username+ "登出成功")
            )
        );
    }
}